package com.kpf.springcloud.service.impl;

import com.kpf.springcloud.common.ResponseEnum;
import com.kpf.springcloud.exception.BusinessException;
import com.kpf.springcloud.mapper.KpfFollowUserMapper;
import com.kpf.springcloud.pojo.KpfFollowUser;
import com.kpf.springcloud.pojo.KpfUser;
import com.kpf.springcloud.service.IKpfFollowUserService;
import com.kpf.springcloud.service.IKpfUserService;
import com.kpf.springcloud.service.ITokenService;
import com.kpf.springcloud.utils.GeneralUtil;
import com.kpf.springcloud.vo.FollowAndFansUserVO;
import com.kpf.springcloud.vo.FollowUserInfoVO;
import com.kpf.springcloud.vo.UserFansAndStatusVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author shiwen
 * @date 2021/4/8
 */
@Service
public class KpfFollowUserServiceImpl extends BaseServiceImpl<KpfFollowUserMapper, KpfFollowUser> implements IKpfFollowUserService {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ITokenService tokenService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IKpfUserService userService;

    @Override
    public void followUser(int followUserId) {
        String token = tokenService.verifyToken();
        if ("TOKEN_EXPIRED".equals(token)) {
            throw new BusinessException(ResponseEnum.TOKEN_EXPIRED);
        }
        int userId = Integer.parseInt(token.split("-")[0]);
        // 获取数据库中存有的对象数据
        KpfFollowUser kpfFollowUser = getOne(getInitQueryWrapper().eq(KpfFollowUser::getFollowUserId, followUserId)
                .eq(KpfFollowUser::getUserId, userId));
        if (GeneralUtil.isObjNull(kpfFollowUser)) {
            // 没有的话则直接保存
            KpfFollowUser newKpfFollowUser = KpfFollowUser.builder().followUserId(followUserId)
                    .userId(userId).followStatus(1).build();
            save(newKpfFollowUser);
        } else {
            // 已有数据, 则判断是否关注, 已关注则变为未关注, 未关注的改为已关注
            if (kpfFollowUser.getFollowStatus() == 0) {
                kpfFollowUser.setFollowStatus(1);
                updateById(kpfFollowUser);
            } else {
                kpfFollowUser.setFollowStatus(0);
                updateById(kpfFollowUser);
            }
        }
    }

    /**
     * 根据关注对象获取关注信息接口
     *
     * @return
     */
    @Override
    public FollowUserInfoVO getFollowInfo() {
        String token = tokenService.verifyToken();
        if ("TOKEN_EXPIRED".equals(token)) {
            throw new BusinessException(ResponseEnum.TOKEN_EXPIRED);
        }
        int userId = Integer.parseInt(token.split("-")[0]);
        String strTopicUserId = stringRedisTemplate.opsForValue().get("kpf:selfUserId");
        int followUserId = Integer.parseInt(strTopicUserId);
        FollowUserInfoVO followUserInfoVO = new FollowUserInfoVO();
        // 获取数据库中存有的对象数据
        KpfFollowUser kpfFollowUser = getOne(getInitQueryWrapper().eq(KpfFollowUser::getFollowUserId, followUserId)
                .eq(KpfFollowUser::getUserId, userId));
        if (GeneralUtil.isObjNull(kpfFollowUser)) {
            // 如果关注对象为空则直接设为没关注
            followUserInfoVO.setFollowStatus(0);
        } else {
            // 已关注的话返回关注的状态
            followUserInfoVO.setFollowStatus(kpfFollowUser.getFollowStatus());
        }
        followUserInfoVO.setFollowCount(count(getInitQueryWrapper().eq(KpfFollowUser::getFollowUserId, followUserId).eq(KpfFollowUser::getFollowStatus, 1)));
        return followUserInfoVO;
    }

    /**
     * 获取关注用户数
     */
    @Override
    public List<FollowAndFansUserVO> getFollowUserList() {
        String strTopicUserId = stringRedisTemplate.opsForValue().get("kpf:selfUserId");
        int followUserId = Integer.parseInt(strTopicUserId);
        List<KpfFollowUser> kpfFollowUserList = list(getInitQueryWrapper().eq(KpfFollowUser::getUserId, followUserId)
                .eq(KpfFollowUser::getFollowStatus, 1));
        if (GeneralUtil.isListNull(kpfFollowUserList)) {
            return new ArrayList<>();
        }
        List<Integer> userIds = kpfFollowUserList.stream().map(KpfFollowUser::getFollowUserId).collect(Collectors.toList());
        List<KpfUser> kpfUserList = userService.list(userService.getInitQueryWrapper().in(KpfUser::getId, userIds));
        // list转map
        Map<Long, KpfUser> kpfUserMap = kpfUserList.stream().collect(Collectors.toMap(KpfUser::getId, Function.identity()));
        List<FollowAndFansUserVO> followAndFansUserVOList = new ArrayList<>();
        kpfFollowUserList.forEach(s -> {
            KpfUser kpfUser = kpfUserMap.get(s.getFollowUserId().longValue());
            FollowAndFansUserVO followAndFansUserVO = FollowAndFansUserVO.builder().headimg(kpfUser.getHeadimg()).id(kpfUser.getId().intValue())
                    .username(kpfUser.getUsername()).userFansAndStatusVO(getUserFansAndStatusVO(followUserId, kpfUser.getId().intValue())).build();
            followAndFansUserVOList.add(followAndFansUserVO);
        });
        return followAndFansUserVOList;
    }

    /**
     * 获取粉丝数
     */
    @Override
    public List<FollowAndFansUserVO> getFansList() {
        String strTopicUserId = stringRedisTemplate.opsForValue().get("kpf:selfUserId");
        int followUserId = Integer.parseInt(strTopicUserId);
        List<KpfFollowUser> kpfFollowUserList = list(getInitQueryWrapper().eq(KpfFollowUser::getFollowUserId, followUserId)
                .eq(KpfFollowUser::getFollowStatus, 1));
        if (GeneralUtil.isListNull(kpfFollowUserList)) {
            return new ArrayList<>();
        }
        List<Integer> userIds = kpfFollowUserList.stream().map(KpfFollowUser::getUserId).collect(Collectors.toList());
        List<KpfUser> kpfUserList = userService.list(userService.getInitQueryWrapper().in(KpfUser::getId, userIds));
        // list转map, 以用户id为主键
        Map<Long, KpfUser> kpfUserMap = kpfUserList.stream().collect(Collectors.toMap(KpfUser::getId, Function.identity()));
        List<FollowAndFansUserVO> followAndFansUserVOList = new ArrayList<>();
        kpfFollowUserList.forEach(s -> {
            KpfUser kpfUser = kpfUserMap.get(s.getUserId().longValue());
            FollowAndFansUserVO followAndFansUserVO = FollowAndFansUserVO.builder().headimg(kpfUser.getHeadimg()).id(kpfUser.getId().intValue())
                    .username(kpfUser.getUsername()).userFansAndStatusVO(getUserFansAndStatusVO(followUserId, kpfUser.getId().intValue())).build();
            followAndFansUserVOList.add(followAndFansUserVO);
        });
        return followAndFansUserVOList;
    }

    /**
     * 根据用户id获取粉丝数和关注状态
     *
     * @param userId
     * @param followUserId
     * @return
     */
    @Override
    public UserFansAndStatusVO getUserFansAndStatusVO(int userId, int followUserId) {
        int fansNum = count(getInitQueryWrapper().eq(KpfFollowUser::getFollowUserId, followUserId).eq(KpfFollowUser::getFollowStatus, 1));
        List<KpfFollowUser> kpfFollowUserList = list(getInitQueryWrapper().eq(KpfFollowUser::getUserId, userId)
                .eq(KpfFollowUser::getFollowUserId, followUserId).eq(KpfFollowUser::getFollowStatus, 1));
        return UserFansAndStatusVO.builder().fansNum(fansNum).followStatus(kpfFollowUserList.size()).build();
    }

}